<script setup>
import { ref, computed, watch } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { getProductDetailApi, updateProductStockApi } from '../api/products'

const router = useRouter()

const cartItems = ref(
  JSON.parse(localStorage.getItem('cartItems') || '[]')
)

watch(
  cartItems,
  newVal => localStorage.setItem('cartItems', JSON.stringify(newVal)),
  { deep: true }
)

const selectAll = computed({
  get() {
    return cartItems.value.length > 0 && cartItems.value.every(item => item.checked)
  },
  set(val) {
    cartItems.value.forEach(item => (item.checked = val))
  }
})

// 修改总价计算方法，确保价格是数字
const totalPrice = computed(() =>
  cartItems.value
    .filter(item => item.checked)
    .reduce((sum, item) => {
      // 确保价格是数字
      const price = typeof item.price === 'string' ? parseFloat(item.price) : item.price
      return sum + price * item.num
    }, 0) * 100
)

const selectedCount = computed(() =>
  cartItems.value.filter(item => item.checked).length
)

const increaseQuantity = async (id) => {
  const item = cartItems.value.find(v => v.id === id)
  if (item) {
    try {
      // 检查库存是否足够
      const productRes = await getProductDetailApi(id)
      if (productRes.success) {
        const currentStock = productRes.data.stock
        if (currentStock > 0) {
          // 增加数量时减少库存
          await updateProductStockApi(id, currentStock - 1)
          item.num++
        } else {
          showToast('库存不足')
        }
      }
    } catch (error) {
      console.error('更新库存失败:', error)
      showToast('操作失败')
    }
  }
}

const decreaseQuantity = async (id) => {
  const item = cartItems.value.find(v => v.id === id)
  if (item && item.num > 1) {
    try {
      // 减少数量时增加库存
      const productRes = await getProductDetailApi(id)
      if (productRes.success) {
        const currentStock = productRes.data.stock
        await updateProductStockApi(id, currentStock + 1)
        item.num--
      }
    } catch (error) {
      console.error('更新库存失败:', error)
      showToast('操作失败')
    }
  }
}

const toggleItemCheck = id => {
  const item = cartItems.value.find(v => v.id === id)
  if (item) item.checked = !item.checked
}

const removeItem = async (id) => {
  const item = cartItems.value.find(v => v.id === id)
  if (item) {
    try {
      // 从购物车删除商品时，将已占用的库存归还
      const productRes = await getProductDetailApi(id)
      if (productRes.success) {
        const currentStock = productRes.data.stock
        // 归还库存：当前库存 + 购物车中的数量
        await updateProductStockApi(id, currentStock + item.num)
      }
    } catch (error) {
      console.error('归还库存失败:', error)
      showToast('删除失败')
      return
    }
  }

  cartItems.value = cartItems.value.filter(v => v.id !== id)
  showToast('商品已删除')
}

const onSubmit = () => {
  const selected = cartItems.value.filter(v => v.checked)
  if (!selected.length) {
    showToast('请至少选择一个商品')
    return
  }
  // 跳转到支付页面
  router.push('/pay')
}
</script>

<template>
  <div class="cart-container">
    <!-- 购物车标题 -->
    <div class="cart-title"><h1>购物车</h1></div>

    <!-- 商品列表 -->
    <div v-if="cartItems.length">
      <van-swipe-cell
        v-for="item in cartItems"
        :key="item.id"
        class="cart-item-container"
      >
        <div class="cart-item">
          <!-- 商品选中复选框 -->
          <div class="checkbox-wrapper">
            <van-checkbox
              v-model="item.checked"
              icon-size="18"
              class="item-checkbox"
            />
          </div>

          <!-- 商品信息展示卡片 -->
          <van-card
            :price="typeof item.price === 'string' ? parseFloat(item.price).toFixed(2) : item.price.toFixed(2)"
            :title="item.title"
            :thumb="item.thumb"
            class="goods-card"
          />

          <!-- 数量控制区域 -->
          <div class="quantity-control">
            <van-button
              square
              size="small"
              text="-"
              :disabled="item.num <= 1"
              @click="decreaseQuantity(item.id)"
              class="quantity-btn"
            />
            <span class="quantity">{{ item.num }}</span>
            <van-button
              square
              size="small"
              text="+"
              @click="increaseQuantity(item.id)"
              class="quantity-btn"
            />
          </div>
        </div>

        <!-- 右侧滑动操作区域 -->
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="removeItem(item.id)"
          />
        </template>
      </van-swipe-cell>
    </div>

    <!-- 空购物车提示 -->
    <div v-else class="empty-cart">
      <van-empty description="购物车为空">
        <van-button round type="primary" @click="$router.push('/')">
          去逛逛
        </van-button>
      </van-empty>
    </div>

    <!-- 结算栏占位 -->
    <div v-if="cartItems.length" class="submit-bar-placeholder" />

    <!-- 结算栏 -->
    <van-submit-bar
      v-if="cartItems.length"
      :price="totalPrice"
      :button-text="`提交订单(${selectedCount})`"
      class="cart-submit-bar"
      @submit="onSubmit"
    >
      <div class="selectAll-wrapper">
        <van-checkbox v-model="selectAll" icon-size="18">全选</van-checkbox>
      </div>
    </van-submit-bar>
  </div>
</template>

<!-- 样式部分保持不变 -->
<style lang="scss" scoped>
/* 购物车容器样式 - 使用主题变量 */
.cart-container {
  min-height: 100vh;
  background: var(--van-background);
  padding-bottom: 100px;
}

/* 购物车标题样式 - 暗色模式适配 */
.cart-title {
  text-align: center;
  padding: 10px;
  background: var(--van-background-2);
  margin-bottom: 10px;
  font-size: 18px;
  color: var(--van-text-color);
  border-bottom: 1px solid var(--van-border-color);
}

/* 购物车项目容器样式 */
.cart-item-container {
  background: var(--van-background-2);
  margin-bottom: 10px;
  border-radius: var(--van-radius-md);
  overflow: hidden;
  box-shadow: var(--van-shadow-1);
}

/* 购物车项目样式 */
.cart-item {
  display: flex;
  align-items: center;
  padding: 10px;
  width: 100%;
}

/* 商品卡片样式 - 暗色模式适配 */
.goods-card {
  flex: 1;
  margin: 0 10px;
  min-width: 0;
  background: transparent;

  :deep(.van-card) {
    background: transparent;
  }

  :deep(.van-card__title) {
    color: var(--van-text-color);
    white-space: normal;
  }

  :deep(.van-card__price) {
    color: var(--van-primary-color);
  }
}

/* 数量控制器样式 - 暗色模式适配 */
.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  min-width: 120px;

  .quantity-btn {
    width: 30px;
    height: 30px;
    background: var(--van-active-color);
    border: 1px solid var(--van-border-color);
    color: var(--van-text-color);
  }

  .quantity {
    color: var(--van-text-color);
    min-width: 30px;
    text-align: center;
  }
}

/* 删除按钮样式 */
.delete-button {
  height: 100%;
}

/* 结算栏样式 - 暗色模式适配 */
:deep(.cart-submit-bar) {
  position: fixed;
  bottom: 50px;
  background: var(--van-background-2);
  border-top: 1px solid var(--van-border-color);

  .van-submit-bar__text,
  .van-submit-bar__price {
    color: var(--van-text-color);
  }

  .van-button {
    background: var(--van-primary-color);
    border: none;
  }
}

/* 复选框样式 - 暗色模式适配 */
:deep(.van-checkbox__label) {
  color: var(--van-text-color);
}

/* 空购物车样式 */
.empty-cart {
  padding: 50px 20px;
  text-align: center;

  :deep(.van-empty__description) {
    color: var(--van-text-color);
  }
}
</style>